package org.geekbang.thinking.in.spring.ioc.dependency.injection.qualifier;

import org.geekbang.thinking.in.spring.ioc.dependency.injection.annotation.UserGroup;
import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**
 * {@link Qualifier} 注解依赖注入
 *
 * @author wangyh2
 * @version v1.0
 * @since 2021-09-25 13:54
 */
public class QualifierAnnotationDependencyInjectionDemo {

    @Autowired
    private User user;

    @Autowired
    @Qualifier("user")
    private User namedUser;

    @Autowired
    private Collection<User> noQualifiedUsers;

    @Autowired
    @Qualifier
    private Collection<User> qualifiedUsers;

    @Autowired
    @UserGroup
    private Collection<User> groupedUsers;

    @Bean
    @Qualifier
    private User user1() {
        return createUser(1L);
    }

    @Bean
    @Qualifier
    private User user2() {
        return createUser(2L);
    }

    @Bean
    @UserGroup
    private User user3() {
        return createUser(3L);
    }

    @Bean
    @UserGroup
    private User user4() {
        return createUser(4L);
    }

    private User createUser(Long id) {
        User user = new User();
        user.setId(id);
        return user;
    }


    public static void main(String[] args) {

        // 1、创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 2、注册 Configuration Class（配置类）
        applicationContext.register(QualifierAnnotationDependencyInjectionDemo.class);
        // 3、加载 XML 资源，解析并且生成 BeanDefinition
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
        String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlBeanDefinitionReader.loadBeanDefinitions(xmlResourcePath);
        // 4、启动 Spring 应用上下文
        applicationContext.refresh();

        // 依赖查找 QualifierAnnotationDependencyInjectionDemo Bean
        QualifierAnnotationDependencyInjectionDemo demo = applicationContext.getBean(QualifierAnnotationDependencyInjectionDemo.class);
        // 期待输出 superUser Bean
        System.out.println(demo.user);
        // 期待输出 user Bean
        System.out.println(demo.namedUser);
        // 期待输出 superUser user
        System.out.println(demo.noQualifiedUsers);
        // 期待输出 user1 user2
        System.out.println(demo.qualifiedUsers);
        // 期待输出 user3 user4
        System.out.println(demo.groupedUsers);
        // 6、显示地关闭 Spring 应用上下文
        applicationContext.close();
    }
}
